package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.permission;

import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.TreeIconSkin;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.MenuMapper;
import com.cqhilink.iot.jobstandardmanagement.facade.model.*;
import com.cqhilink.iot.jobstandardmanagement.facade.service.permission.JsmMenuButtonService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.permission.JsmMenuService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.permission.JsmSystemPlatformService;
import com.cqhilink.iot.jobstandardmanagement.services.redisservice.RedisClientTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by huangxueqian on 2017/1/6/006.
 * 菜单服务控制实现类
 */

public class JsmMenuServiceImpl implements JsmMenuService {
    public Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private JsmMenuButtonService buttonService;

    @Autowired
    private RedisClientTemplate redisClientTemplate;

    @Autowired
    private JsmSystemPlatformService jsmSystemPlatformService;


    /**
     * @param url 查询url查询到最高层级
     */
    @Override
    public Menu getFirstByUrl(String url, String employeeId) throws Exception {
        Map map = new HashMap<>();
        map.put("url", url);
        Menu odm = menuMapper.selectMenuByUrl(map);
        if (!StringUtils.isEmpty(odm)) {
            map.put("subSystemCode", odm.getSystemPlatformId());
            Menu menu = menuMapper.selectFirstMenuByUrl(map);
            redisClientTemplate.set(menu.getSystemPlatformId() + employeeId, menu.getMenuId());
            return menu;
        } else {
            redisClientTemplate.set(odm.getSystemPlatformId() + employeeId, odm.getMenuId());
            return odm;
        }
    }


    /**
     * @param systemCode 系统编码
     * @param roleMenus  角色菜单集
     * @return 返回顶级菜单
     * @throws Exception 抛出异常
     */
    @Override
    public List<Menu> getFirstLevelMenu(String systemCode, List<RoleMenu> roleMenus, boolean isAdmin) throws Exception {
        // 菜单问题修改
        List<SystemPlatform>  sysList = jsmSystemPlatformService.selectAllSystemPlatform();
        List<Menu> menus = new ArrayList<>();
        if (!roleMenus.isEmpty()) {
                /* 判断角色菜单是否为空，不为空进行查询菜单信息 */
            for (RoleMenu roleMenu : roleMenus) {
                Menu menu = menuMapper.selectByPrimaryKey(roleMenu.getMenuId());

                if(sysList != null && sysList.size() > 0){
                        for(SystemPlatform systemPlatform:sysList){
                            logger.info("------------>"+menu.getParentMenuId() + "------->"+menu.getParentMenuId().equals(systemPlatform.getSystemCode()));
                            if (menu != null && menu.getParentMenuId().equals(systemPlatform.getSystemCode())) {
                                menus.add(menu);
                             }
                        }
                }
            }
        }
        return menus;
    }

    /**
     * @param systemCode 系统编码
     * @param menuId     点击的一级菜单ID
     * @param employeeVo 当前登录人信息
     * @return 获取当前系统问题数据问题
     * @throws Exception
     */
    @Override
    public List<Menu> getAfterLevelMenu(String systemCode, String menuId, EmployeeVo employeeVo, boolean isAdmin) throws Exception {
        Map selMap = new HashMap<>();
        selMap.put("menuId", menuId);
        selMap.put("systemCode", systemCode);
        selMap.put("employeeId", employeeVo.getEmployeeId());
        selMap.put("isAdmin", isAdmin);
        return menuMapper.selectAfterMenu(selMap);
    }

    /**
     * @param menu 菜单新增
     * @return 返回菜单新增界面
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer menuAdd(Menu menu,Employee employee) throws Exception {
        Integer resInt = 0;
        if (menu.getMenuId() == null) {
            menu.setMenuId(UniqueUtil.uuid());
            menu.setModifier(employee.getEmployeeId());
            menu.setModifyDate(new Date());
            menu.setCreateDate(new Date());
            menu.setCreator(employee.getEmployeeId());
            /* 新增菜单 */
            resInt = menuMapper.insertSelective(menu);
            if (menu.getParentMenuId() != null) {
                Menu menuP = menuMapper.selectByPrimaryKey(menu.getParentMenuId());
                if(menuP != null){
                    menuP.setRemark1("1"); // 将父亲节点设置
                    resInt = resInt +  menuMapper.updateByPrimaryKeySelective(menuP);
                }
            }
        } else {
            menu.setModifier(employee.getEmployeeId());
            menu.setModifyDate(new Date());
            /* 更新菜单 */
            resInt = resInt+ menuMapper.updateByPrimaryKeySelective(menu);
        }
        // 菜单按钮问题
        if(org.apache.commons.lang.StringUtils.isNotEmpty(menu.getButtonList())) {
            resInt = resInt +  buttonService.insertList(menu,employee);
        }
        // 删除菜单按钮

        return resInt;
    }

    /**
     * 根据菜单唯一标识，删除菜单
     *
     * @param menuId 菜单唯一标识
     * @throws Exception
     */
    @Override
    public Integer menuDel(String menuId) throws Exception {
        return menuMapper.deleteByPrimaryKey(menuId);
    }

    /**
     * 获取所有菜单进行管理
     *
     * @return
     */
    @Override
    public List<Menu> loadMenuAll() throws Exception {
        return menuMapper.selectAllMenu();
    }

    /**
     * @param menuId 菜单ID
     * @return 查询菜单名称
     * @throws Exception
     */
    @Override
    public Menu selectMenu(String menuId) throws Exception {
        return menuMapper.selectByPrimaryKey(menuId);
    }

    /**
     * 根据条件查询
     *
     * @param selectMap
     * @return
     */
    @Override
    public List<Menu> selectListMenu(Map selectMap) {
        return menuMapper.selectMenuList(selectMap);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量添加
     * @Date 2017/2/8 18:09
     */
    @Override
    public int insertList(List<Menu> list) {
        return menuMapper.insertList(list);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量逻辑删除
     * @Date 2017/2/8 17:18
     */
    @Override
    public int updateList(List<Menu> list) {
        return menuMapper.updateList(list);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量逻辑删除
     * @Date 2017/2/8 18:09
     */
    @Override
    public int deleteList(List<Menu> list) {
        return menuMapper.deleteList(list);
    }


    /**
     * @param rolesId 角色Id ;
     * @param isAdmin true 超级管理员 ；
     *                false 管理员 和 普通管理员 ;
     */
    @Override
    public List<Menu> selectMenuList(String rolesId, String menuId, boolean isAdmin) throws Exception {
        Map map = new HashMap<>();
        map.put("isAdmin", isAdmin + "");
        map.put("menuId", menuId);
        map.put("rolesId", rolesId);
        return menuMapper.selectMenuList(map);
    }

    /**
     * 根据条件查询ID集合
     *
     * @param list
     * @return
     */
    @Override
    public List<String> selectByListId(List<Menu> list) {
        return menuMapper.selectByListId(list);
    }

    @Override
    public List<Menu> getAllMenuPermission(String systemCode, EmployeeVo employeeVo) throws Exception {
        return menuMapper.getAllMenuPermission(employeeVo);
    }

    /**
     * @param keyword 模糊查询
     */
    @Override
    public List<Ztree> noAjaxLoadMenuZtree(String keyword) throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        // 条件查询不为空
        if (org.apache.commons.lang.StringUtils.isNotEmpty(keyword)) {
            logger.info("keyword-->不为空的情况--keyword=" + keyword);
            Menu menu = new Menu();
            menu.setMenuName(keyword);
            List<Menu> keywordMenuList = menuMapper.selectByKeyWord(menu);
            Map<String, String> spfMap = new HashMap<>();
            // 判断是否查询出sql菜单 ，
            if (keywordMenuList != null && keywordMenuList.size() > 0) {
                // 查询出顶级菜单
                for (Menu mu : keywordMenuList) {
                    Ztree ztree = new Ztree();
                    ztree.setId(mu.getMenuId());
                    ztree.setName(mu.getMenuName());
                    ztree.setpId(mu.getParentMenuId());
                    ztree.setIconSkin(TreeIconSkin.ICON_MENU.getDesc());
                    ztree.setOpen(true);
                    ztreeList.add(ztree);
                    if (org.apache.commons.lang.StringUtils.isNotEmpty(mu.getSystemPlatformId())) {
                        spfMap.put(mu.getSystemPlatformId(), mu.getSystemPlatformId());
                    }
                }
            }
            // 查询平台类型
            if (spfMap != null && spfMap.size() > 0) {
                for (Map.Entry<String, String> entry : spfMap.entrySet()) {
                    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
                    String spfId = entry.getKey();
                    SystemPlatform spf = jsmSystemPlatformService.selectByPrimaryKey(spfId);
                    Ztree ztree = new Ztree();
                    ztree.setId(spf.getSystemCode());
                    ztree.setName(spf.getSystemPlatformName());
                    ztree.setpId("#");
                    ztree.setIconSkin(TreeIconSkin.ICON_SUBSYSTEM.getDesc());
                    ztree.setOpen(true);
                    ztreeList.add(ztree);
                }
            }

        } else {
            // 条件查询为空
            logger.info("keyword-->为空的情况--keyword=" + keyword);
            try {
                     /*对平台子系统进行控制*/
                List<SystemPlatform> systemPlatforms = jsmSystemPlatformService.selectAllSystemPlatform();
                List<Menu> menus = menuMapper.selectAllMenu();
                if (systemPlatforms != null) {
                    /**
                     *平台问题
                     */
                    for (SystemPlatform systemPlatform : systemPlatforms) {
                        Ztree ztree = new Ztree();
                        ztree.setId(systemPlatform.getSystemCode());
                        ztree.setName(systemPlatform.getSystemPlatformName());
                        ztree.setpId(systemPlatform.getParentPlatformId());
                        ztree.setIconSkin(TreeIconSkin.ICON_SUBSYSTEM.getDesc());
                        ztree.setOpen(true);
                        ztreeList.add(ztree);
                    }
                }
                    /* 菜单控制 */
                if (menus != null) {
                    for (Menu menu : menus) {
                        Ztree ztree = new Ztree();
                        ztree.setId(menu.getMenuId());
                        ztree.setName(menu.getMenuName());
                        ztree.setpId(menu.getParentMenuId());
                        ztree.setIconSkin(TreeIconSkin.ICON_MENU.getDesc());
                        ztree.setOpen(false);
                        ztreeList.add(ztree);
                    }
                }
            } catch (Exception e) {
                logger.error("loadMenuTree-->" + e.getLocalizedMessage());
                e.printStackTrace();
            }

        }
        return ztreeList;
    }

    @Override
    public List<Ztree> queryChildMenuZtree(String menuId) throws Exception {
        List<Ztree> menuZtreeList = new ArrayList<>();
        List<Menu> menuList =  menuMapper.queryMenuChild(menuId);
        if(menuList!=null && menuList.size() > 0){
                for(Menu menu : menuList){
                        Ztree ztree = new Ztree();
                        ztree.setId(menu.getMenuId());
                        ztree.setName(menu.getMenuName());
                        ztree.setpId(menu.getParentMenuId());
                        ztree.setIconSkin(TreeIconSkin.ICON_MENU.getDesc());
                        ztree.setOpen(true);
                        ztree.setIsParent(false);
                        menuZtreeList.add(ztree);
                }
        }
        return menuZtreeList;
    }

    /**
     *
     * @param menuName 菜单名称
     * @param systemId 菜单所属子系统
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> authMenu(String menuName, String systemId,EmployeeVo employeeVo) throws Exception {
        Map<String,String> param = new HashMap<>() ;
        Map<String,Object> resMap =  new HashMap<>() ;
        param.put("menuName",menuName);
        param.put("systemId",systemId);
        param.put("employeeId",employeeVo.getEmployeeId());
        List<Menu> menu = menuMapper.authMenu(param) ;
        if(menu != null && menu.size() > 0){
            resMap.put("state",true);
        }else{
            resMap.put("state",false);
        }
        return resMap;
    }
}
